<template>
  <div class="main-container">
    <button
      v-show="!isSidebarVisible"
      @click="toggleSidebar"
      class="sidebar-trigger"
    >☰</button>

    <Sidebar
      :isSidebarVisible="isSidebarVisible"
      :userEmail="userEmail"
      :isLoggedIn="isLoggedIn"
      @toggle="toggleSidebar"
      @logout="handleLogout"
      @login="showLoginModal"
    />
    <main class="content" :class="{ expanded: !isSidebarVisible }">
      <ChatArea :isLoggedIn="isLoggedIn" @send="showLoginModal" />
    </main>
    <LoginModal
      :isVisible="isLoginModalVisible"
      @close="isLoginModalVisible = false"
      @login="handleLogin"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Sidebar from '@/components/Sidebar.vue';
import ChatArea from '@/components/ChatArea.vue';
import LoginModal from '@/components/LoginModal.vue';

const isSidebarVisible = ref(true);
const isLoginModalVisible = ref(false);
const isLoggedIn = ref(false); // 登录状态
const userEmail = ref(''); // 存储用户邮箱

const toggleSidebar = () => {
  isSidebarVisible.value = !isSidebarVisible.value;
};

// 修改这里，添加显示登录框的方法
const showLoginModal = () => {
  isLoginModalVisible.value = true;
};

// 检查本地存储的登录状态
onMounted(() => {
  const storedToken = localStorage.getItem('token');
  const storedUserInfo = JSON.parse(localStorage.getItem('userInfo'));
  
  if (storedToken && storedUserInfo) {
    isLoggedIn.value = true;
    userEmail.value = storedUserInfo.email;
  }
});

const handleLogin = async (userData) => {
  console.log('[Login] 开始处理登录数据');
  
  // 先存储数据
  localStorage.setItem('token', userData.token);
  localStorage.setItem('userInfo', JSON.stringify({
      email: userData.email,
      username: userData.username
  }));
  console.log('[Login] Token已存储:', userData.token);
  
  // 更新状态
  userEmail.value = userData.email;
  isLoggedIn.value = true;
  isLoginModalVisible.value = false;

  // 确保 token 存储后再启动定时器
  await import('@/utils/tokenManager').then(({ default: tokenManager }) => {
      tokenManager.startRefreshTimer();
  });
};

// 添加登出方法
const handleLogout = () => {
  console.log('[Logout] 开始处理登出');
  localStorage.removeItem('token');
  localStorage.removeItem('userInfo');
  isLoggedIn.value = false;
  userEmail.value = '';
};
</script>

<style scoped>
.main-container {
  height: 100vh;
  display: flex;
  position: relative;
  background: #f0f2f5;
  overflow: hidden;
}

.sidebar-trigger {
  position: fixed;
  left: 20px;
  top: 20px;
  background: #ffffff;
  color: #333;
  border: 1px solid #ccc;
  padding: 12px 16px;
  border-radius: 6px;
  cursor: pointer;
  z-index: 999;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.content {
  flex: 1;
  margin-left: 0;
  transition: margin-left 0.3s ease;
}
</style>